<template>
  <view class="main">
    <!-- 标题 -->
    <view class="text">
      <input
        type="text"
        v-model="editObj.title"
        placeholder="请输入标题"
        @click="toolShow = true"
      >
    </view>

    <!-- 内容 -->
    <view class="content">
      <editor
        id="editor"
        show-img-size
        show-img-toolbar
        show-img-resize
        v-model="editorValue"
        @ready="ready"
        @focus="focus"
        @statuschange="statuschange"
        placeholder="写点什么吧"
      >
      </editor>
    </view>

    <!-- 工具 -->
    <view
      class="tools"
      v-if="toolShow"
    >

      <view class="items">
        <!-- 字号 -->
        <view
          class="iconfont icon-H "
          :class="headShow?'active':''"
          @click="clickHead('header','h2')"
        ></view>
        <!-- 加粗 -->
        <view
          class=" iconfont icon-cuti"
          :class="boldShow?'active':''"
          @click="clickBold('bold')"
        ></view>
        <!-- 斜体 -->
        <view
          class="iconfont icon-zitixieti"
          :class="italicShow?'active':''"
          @click="clickItalic('italic')"
        >
        </view>
        <!-- 分割线 -->
        <view
          class="iconfont icon-hr"
          @click="clickHr"
        ></view>
        <!-- 图片 -->
        <view
          class="iconfont icon-tupian"
          @click="clickImage"
        ></view>
        <!-- 对号 -->
        <view
          class="iconfont icon-duihao"
          @click="clickShow"
        ></view>
      </view>
      <view class="btn">
        <u-button
          v-if="isShow"
          type="primary"
          :disabled="btnShow"
          @click="getEdit"
        >确认发表</u-button>
        <u-button
          v-else
          type="primary"
          :disabled="btnShow"
          @click="updateEdit"
        >确认修改</u-button>
      </view>
    </view>
  </view>
</template>

<script>
import { getImgSrc, getProvince } from "../../utils/tools.js";

const db = uniCloud.database();
export default {
  data() {
    return {
      headShow: false,
      boldShow: false,
      italicShow: false,
      toolShow: false,
      editObj: {
        title: "",
        content: "",
        description: "",
        picurls: "",
        province: ""
      },
      editorValue: {},
      btnShow: true,
      isShow: false,
      articleId: ""
    };
  },
  onLoad(e) {
    this.articleId = e.id;
    if (e.id == undefined) {
      this.isShow = true;
    } else {
      this.getUpdateEdit();
    }
  },
  computed: {
    listenChange() {
      let editorValue = this.editorValue.target;
      let editObj = this.editObj.title;
      return { editorValue, editObj };
    }
  },
  watch: {
    // 监听title和富文本内容是否为空,为空则不能发布文章
    listenChange: {
      handler(newVal) {
        if (
          newVal.editorValue != undefined &&
          newVal.editObj.length > 0 &&
          newVal.editorValue != null
        ) {
          this.btnShow = false;
        } else {
          this.btnShow = true;
        }
      }
    }
  },
  methods: {
    // 获取文章信息
    async getUpdateEdit() {
      let { result } = await db
        .collection("quanzi_article")
        .doc(`${this.articleId}`)
        .get();
      this.editObj = result.data[0];
      this.editorCtx.setContents({
        html: result.data[0].content
      });
      this.editorValue.target = result.data[0].content;
    },
    // 更新文章
    async updateEdit() {
      this.editorCtx.getContents({
        success: async res => {
          this.editObj.content = res.html;
          this.editObj.description = res.text.slice(0, 80);
          this.editObj.picurls = getImgSrc(res.html);
        }
      });
      let upObj = {
        content: this.editObj.content,
        title: this.editObj.title,
        description: this.editObj.description,
        picurls: this.editObj.picurls
      };
      let { result } = await db
        .collection("quanzi_article")
        .doc(`${this.articleId}`)
        .update({
          ...upObj
        });
      if (result.errCode == 0) {
        uni.showToast({
          title: "修改成功",
          icon: "success"
        });
         uni.switchTab({
            url: "/pages/index/index"
          });
      } else {
        uni.showToast({
          title: "修改失败",
          icon: "error"
        });
      }
    },
    // 点击按钮添加博客富文本内容
    getEdit() {
      this.editorCtx.getContents({
        success: async res => {
          this.editObj.description = res.text.slice(0, 80);
          this.editObj.content = res.html;
          this.editObj.picurls = getImgSrc(res.html);
          // 获取用户地理位置
          let data = await getProvince();
          this.editObj.province = data;
          // 文本数据填充,调用增加数据接口
          this.addData();
        }
      });
    },
    async addData() {
      let { result } = await db.collection("quanzi_article").add({
        ...this.editObj
      });
      if (result.errCode == 0) {
        uni.showToast({
          title: "添加成功",
          icon: "success"
        });
        setTimeout(() => {
          uni.switchTab({
            url: "/pages/index/index"
          });
        }, 1500);
      } else {
        uni.showToast({
          title: "添加失败",
          icon: "error"
        });
      }
    },
    // input获取焦点
    focus() {
      this.toolShow = true;
    },
    // 进入页面加载editor组件,并获取该组件的节点信息
    ready() {
      uni
        .createSelectorQuery()
        .in(this)
        .select("#editor")
        .fields(
          {
            size: true,
            context: true
          },
          res => {
            this.editorCtx = res.context;
          }
        )
        .exec();
    },
    // 点击分割线
    clickHr() {
      this.editorCtx.insertDivider();
    },
    // 点击设置字号
    clickHead(name, value) {
      this.headShow = !this.headShow;
      this.editorCtx.format(name, this.headShow ? value : false);
    },
    // 设置加粗
    clickBold(name) {
      this.boldShow = !this.boldShow;
      this.editorCtx.format(name);
    },
    // 设置加粗
    clickItalic(name) {
      this.italicShow = !this.italicShow;
      this.editorCtx.format(name);
    },
    // 隐藏工具栏
    clickShow() {
      this.toolShow = false;
    },
    // 查询工具状态
    ckeckChange(name, detail, obj) {
      if (detail.hasOwnProperty(name)) {
        this[obj] = true;
      } else {
        this[obj] = false;
      }
    },
    // 当样式发生改变
    statuschange(e) {
      let detail = e.detail;
      this.ckeckChange("header", detail, "headShow");
      this.ckeckChange("italic", detail, "italicShow");
      this.ckeckChange("bold", detail, "boldShow");
    },
    // 上传图片
    clickImage() {
      uni.chooseImage({
        count: 9, //默认9
        sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album"], //从相册选择
        success: async res => {
          uni.showLoading({
            title: "上传中"
          });

          for (let item of res.tempFiles) {
            let result = await uniCloud.uploadFile({
              filePath: item.path,
              cloudPath: item.name
            });
            this.editorCtx.insertImage({
              src: result.fileID
            });
          }
          uni.hideLoading();
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.iconfont {
  font-size: 38rpx;
}

.main {
  overflow: hidden;

  .text {
    margin-top: 20rpx;
    padding: 0 20rpx;

    /deep/.uni-input-placeholder {
      font-size: 40rpx;
      color: #999;
    }
  }

  .content {
    padding: 0 20rpx;
    margin-top: 30rpx;

    #editor {
      height: calc(100vh - 500rpx);

      /deep/img {
        max-width: 9rem;
        max-height: 12rem;
      }
    }
  }

  .tools {
    height: 200rpx;
    position: fixed;
    bottom: 0;
    width: 100%;
    background-color: #fff;

    .items {
      border-bottom: 2rpx solid #eee;
      height: 40%;
      padding: 0 20rpx;
      display: flex;
      justify-content: space-around;
      align-items: center;

      .active {
        color: #3c9cff;
      }
    }

    .btn {
      margin: 20rpx 0;
      padding: 0 20rpx;
    }
  }
}
</style>
